package com.qf.sevice.Impl;

import com.qf.dao.AddressDao;
import com.qf.dao.Impl.AddressDaoImpl;
import com.qf.dao.Impl.OrderDaoImpl;
import com.qf.dao.OrderDao;
import com.qf.domain.Address;
import com.qf.domain.Order;
import com.qf.sevice.AddressService;
import com.qf.utils.TxUtils;
import org.apache.commons.dbutils.QueryRunner;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class AddressServiceImpl implements AddressService {
    AddressDao addressDao = new AddressDaoImpl();
    @Override
    public List<Address> findAddListByUid(int uid) {
        return addressDao.findAddListByUid(uid);
    }

    @Override
    public void insert(Address address) {
        addressDao.insert(address);
    }
    OrderDao orderDao = new OrderDaoImpl();
    @Override
    public void deleteById(String id) {
        Long count=orderDao.findCountByAid(id);
        if (count == 0){
            addressDao.delectById(id);
        }else{
            System.out.println("与订单关联不能删除!!");
        }
    }

    @Override
    public void update(Address address) {
        addressDao.update(address);
    }

    @Override
    public void setDefaultAddress(String aid, int uid) {
        Connection conn = TxUtils.getConn();
        try {
            conn.setAutoCommit(false);
            addressDao.clearDefaultAddress(uid);//设置都不是默认
            addressDao.setDefalutAddress(aid);//设置某个为默认地址
            conn.commit();
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            TxUtils.remove();
            try {
                conn.setAutoCommit(true);
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}
